package com.ayjsolutions.marcadoresfutbol.service;

import java.util.Calendar;
import java.util.List;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.ayjsolutions.marcadoresfutbol.MainActivity;
import com.ayjsolutions.marcadoresfutbol.PartidoLista;
import com.ayjsolutions.marcadoresfutbol.R;
import com.ayjsolutions.marcadoresfutbol.database.DBPartidosLista;
import com.ayjsolutions.marcadoresfutbol.util.Utiles;

public class UpdateService extends IntentService {

	public UpdateService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}
	
	public UpdateService() {
		super("UpdateService");
		// TODO Auto-generated constructor stub
	}

	private final IBinder mBinder = new MyBinder();
	public static Calendar lastDay = null;
	private Context context;


	public class MyBinder extends Binder {
		public UpdateService getService() {
			return UpdateService.this;
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}

	/**
	 * Checks if the update necessary.
	 * 
	 * @return true, if update necessary
	 */
	public boolean isUpdateNecessary() {

		Calendar today = Calendar.getInstance();

		DBPartidosLista basedatos = new DBPartidosLista(context);

		basedatos.open();
		String date = basedatos.getDBDate();
		basedatos.close();

		if (date.equals(today.toString())) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		context = getApplicationContext();

		DBPartidosLista basedatos = new DBPartidosLista(context);

		Log.i("REFRESH", "REFRESHING PARTIDOS");

		Utiles.startDatabaseSession(context, 2);

		basedatos.open();
		List<PartidoLista> partidosUpdate = basedatos.getPartidosToUpdate();
		basedatos.close();

		if (!partidosUpdate.isEmpty()) {

			List<PartidoLista> partidosNuevos = Utiles
					.getPartidosFromSoccerWay(context, Utiles.URL_FLASHSCORE);
			basedatos.open();
			List<PartidoUpdated> state = basedatos.updatePartido(
					partidosUpdate, partidosNuevos, context);
			basedatos.close();

			Log.i("REFRESH", state.size() + " matches to refresh");

			for (PartidoUpdated partido : state) {

				String notification = null;
				String result = null;
				int drawing = R.drawable.soccer;

				if (partido.getStates()[0]) {
					// GOAL
					notification = "Goal";
					result = partido.getHomeTeam() + " "
							+ partido.getHomeGoals() + " - "
							+ partido.getVisitorGoals() + " "
							+ partido.getVisitorTeam() + "("
							+ partido.getTime().replace(" ", "") + ")";
				} else if (partido.getStates()[1]) {
					notification = "End of match";
					result = partido.getHomeTeam() + " "
							+ partido.getHomeGoals() + " - "
							+ partido.getVisitorGoals() + " "
							+ partido.getVisitorTeam();
				} else if (partido.getStates()[2]) {
					notification = "Start of match";
					result = partido.getHomeTeam() + " - "
							+ partido.getVisitorTeam();
				} else {
					// Nothing to report, we move to the next match
					continue;
				}
				
				Log.i("REFRESH",
						"REFRESHING PARTIDO ID "
								+ partido.getId()
								+ " with state "
								+ Boolean.toString(partido.getStates()[0]
										|| partido.getStates()[1]
										|| partido.getStates()[2]));

				long[] a = { 0, 300, 300, 300 };

				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						context).setSmallIcon(drawing)
						.setContentTitle(notification).setContentText(result)
						.setVibrate(a);
				Intent resultIntent = new Intent(context, MainActivity.class);
				TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
				stackBuilder.addParentStack(MainActivity.class);
				stackBuilder.addNextIntent(resultIntent);
				PendingIntent resultPendingIntent = stackBuilder
						.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				mNotificationManager.notify((int) (long) partido.getId(),
						mBuilder.getNotification());

			}
		}
		
	}

}
